------------------------------------------
function split(str, pat)
   local t = {}  -- NOTE: use {n = 0} in Lua-5.0
   local fpat = "(.-)" .. pat
   local last_end = 1
   local s, e, cap = str:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
    table.insert(t,cap)
      end
      last_end = e+1
      s, e, cap = str:find(fpat, last_end)
   end
   if last_end <= #str then
      cap = str:sub(last_end)
      table.insert(t, cap)
   end
   return t
end
-------------------------------------------

dofile ("libFormes.lua")

RadioButton = {}

function RadioButton.init (nbr, x, y, text)
  local nb = tostring (nbr)
  
  _G[nb] = {}
  
  _G[nb].x = x+4
  _G[nb].y = y+4
  _G[nb].rayon = 4
  _G[nb].stxwx = x+13
  _G[nb].stxwy = y
  _G[nb].text = split (text, "/")
  _G[nb].nbbut = table.getn (_G[nb].text)
  _G[nb].bxx = 0
  _G[nb].bxy = 0
  _G[nb].bx[nbbut] = newBox (_G[nb].x1, _G[nb].y1, _G[nb].stxwx+string.len (_G[nb].text)*6, _G[nb].y2)
  _G[nb].c1 = c_noir
  _G[nb].c2 = c_blanc
  _G[nb].sel = false
  
end

function RadioButton.draw (nbr)
  local nb = tostring (nbr)
  
  if Stylus.held then
    _G[nb].bxx = Stylus.X
    _G[nb].bxy = Stylus.Y
  end
  
  screen.print (SCREEN_DOWN, _G[nb].stxwx, _G[nb].stxwy, _G[nb].text)
  screen.drawFillCircle  (SCREEN_DOWN, _G[nb].x, _G[nb].y, _G[nb].rayon, _G[nb].c1)
  screen.drawCircle (SCREEN_DOWN, _G[nb].x, _G[nb].y, _G[nb].rayon, c_blanc)
  if Stylus.newPressinBox (_G[nb].bx, _G[nb].bxx, _G[nb].bxy) and _G[nb].sel == false then
    _G[nb].c1 = c_blanc
    _G[nb].c2 = c_noir
    _G[nb].sel = true
  elseif Stylus.newPressinBox (_G[nb].bx, _G[nb].bxx, _G[nb].bxy) and _G[nb].sel == true then
    _G[nb].c1 = c_noir
    _G[nb].c2 = c_blanc
    _G[nb].sel = false
  end
end

function RadioButton.selected (nbr)
  local nb = tostring (nbr)
  
  return _G[nb].sel
end

function RadioButton.clear (nbr)
  local nb = tostring (nbr)
  
  _G[nb] = nil
end
